package edu.whu.notepal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.whu.notepal.dto.SocketBean;
import edu.whu.notepal.pojo.Contacts;
import edu.whu.notepal.service.ContactsService;
import edu.whu.notepal.mapper.ContactsMapper;
import edu.whu.notepal.utils.MessageType;
import edu.whu.notepal.utils.MyWebSocket;
import edu.whu.notepal.utils.RedisConstants;
import edu.whu.notepal.utils.SocketBeanFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 陈磊
* @description 针对表【t_contacts】的数据库操作Service实现
* @createDate 2022-12-02 15:40:04
*/
@Service
public class ContactsServiceImpl extends ServiceImpl<ContactsMapper, Contacts>
    implements ContactsService {

    @Resource
    MyWebSocket myWebSocket;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Contacts> getFriendsById(Long ownerId) {
        LambdaQueryWrapper<Contacts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contacts::getOwnerId, ownerId);
        wrapper.select(Contacts::getFriendId);
        List<Contacts> list = this.list(wrapper);
        return list;
    }

    private void deleteActive(Long ownerId, Long friendId){
        stringRedisTemplate.delete(RedisConstants.CONTACTS_USER_KEY+ownerId);
        LambdaQueryWrapper<Contacts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contacts::getOwnerId,ownerId);
        wrapper.eq(Contacts::getFriendId,friendId);
        this.remove(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBiDirection(Long ownerId, Long friendId) {
        deleteActive(ownerId,friendId);
        deleteActive(friendId,ownerId);
    }

    public void saveActive(Long ownerId,Long friendId){
        stringRedisTemplate.delete(RedisConstants.CONTACTS_USER_KEY+ownerId);
        Contacts contacts = new Contacts();
        contacts.setOwnerId(ownerId);
        contacts.setFriendId(friendId);
        save(contacts);
        SocketBean socketBean = SocketBeanFactory.instance
                (ownerId,friendId, MessageType.FRIEND_ACCESS,"你们已成为好友",null);
        myWebSocket.sendToOne(socketBean);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBiDirection(Long ownerId,Long friendId) {
        saveActive(ownerId,friendId);
        saveActive(friendId,ownerId);
    }

    @Override
    public Boolean judgeFriend(Long ownerId, Long friendId) {
        LambdaQueryWrapper<Contacts> contactsWrapper = new LambdaQueryWrapper<>();
        contactsWrapper.eq(Contacts::getOwnerId,ownerId);
        contactsWrapper.eq(Contacts::getFriendId,friendId);
        return null!=getOne(contactsWrapper);
    }

}